package com.bsu.ascm.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class BsuHttpClient {
	protected String url = "";										//域名或IP
	protected String encoding = "";									//字符编码
	private String type = "application/x-www-form-urlencoded";		//设置请求类型	
	private HttpPost httppost = null;								//post对象
	private HttpGet httpget = null;									//get对象
	private StringEntity reqEntity = null;							//参数实体
	private HttpResponse response = null;							//响应数据对象
	private DefaultHttpClient httpclient = new DefaultHttpClient();	//默认http客户端
	private HttpEntity entity = null;								//返回响应的http实体
	private BufferedReader reader = null;							//读取对象
	
	public BsuHttpClient(){} 
	/**
	 * 设置访问地址与数据编码
	 * @param u		访问地址
	 * @param ed	数据编码
	 */
	public void setParams(String u,String ed){
		url = u;
		encoding = ed;
	} 
	
	/**
	 * 请求数据 get方式
	 * @param param	url参数
	 * @return		返回响应数据
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String getData(String param) throws ClientProtocolException, IOException{
		StringBuffer retsb = new StringBuffer("");
		httpget = new HttpGet(url+param);
		response = httpclient.execute(httpget);
		entity = response.getEntity();
		
		if(entity != null){
			reader = new BufferedReader(new InputStreamReader(entity.getContent(),encoding));
			String s = null;
			while((s = reader.readLine()) != null)
				retsb.append(s);
			entity.consumeContent();
		}
		return retsb.toString();
	}
	
	/**
	 * 请求数据
	 * @param data	发送的数据
	 * @return		返回响应的数据
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	public String postData(String data) throws ClientProtocolException, IOException{
		StringBuffer retsb = new StringBuffer("");
		httppost = new HttpPost(url);							//设置要访问的页面
		reqEntity = new StringEntity(data);						//请求参数实体
		reqEntity.setContentType(type);							//设置请求参数类型
		httppost.setEntity(reqEntity);							//post对象关联
		response = httpclient.execute(httppost);				//获得返回对象
		entity = response.getEntity();
		 
		if(entity != null){
			reader = new BufferedReader(new InputStreamReader(entity.getContent(),encoding));
			String s = null;
			while((s = reader.readLine())!= null)
				retsb.append(s);
			entity.consumeContent();
		}
		return retsb.toString();
	}

}
